package com.dartsstats.datasource;

import com.dartsstats.Game;
import com.dartsstats.DM.GameDM;
import com.dartsstats.DM.MatchDM;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class GameDataSource {

	
	private SQLiteDatabase database;
	private GameDM gameDM;
	private String[] allColumns = { GameDM.COLUMN_ID, GameDM.COLUMN_MATCH,  GameDM.COLUMN_GAME_NUMBER, GameDM.COLUMN_HOME_SCORE, GameDM.COLUMN_AWAY_SCORE};
	
	public GameDataSource(Context context) {
		gameDM = new GameDM(context);
	}
	
	public void open() throws SQLException {
		database = gameDM.getWritableDatabase();
	}
	
	public void close() {
		gameDM.close();
	}
	
	public Game createGame(long match, int gameNumber, int homeScore, int awayScore){
		openDatabaseIfNull();
		ContentValues values = new ContentValues();
		values.put(GameDM.COLUMN_MATCH, match);
		values.put(GameDM.COLUMN_GAME_NUMBER, gameNumber);
		values.put(GameDM.COLUMN_HOME_SCORE, homeScore);
		values.put(GameDM.COLUMN_AWAY_SCORE, awayScore);
		long insertId = database.insert(GameDM.TABLE_GAME, null, values);
		Cursor cursor = database.query(GameDM.TABLE_GAME, allColumns, GameDM.COLUMN_ID + " = " + insertId, null, null, null, null);
		cursor.moveToFirst();
		Game game = cursorToGame(cursor);
		cursor.close();
		return game;
	}
	
	public void updateGame(Game game) {
		openDatabaseIfNull();
		ContentValues values = new ContentValues();
		values.put(GameDM.COLUMN_HOME_SCORE, game.getHomeScore());
		values.put(GameDM.COLUMN_AWAY_SCORE, game.getAwayScore());
		String[] whereArgs = new String[] {String.valueOf(game.getId())};
		database.update(GameDM.TABLE_GAME, values, GameDM.COLUMN_ID + " = ?", whereArgs);
	}
	
	public Game getGameByID(int gameID) {
		openDatabaseIfNull();
		String[] whereArgs = new String[] {String.valueOf(gameID)};
		Cursor cursor = database.query(GameDM.TABLE_GAME, allColumns, GameDM.COLUMN_ID + " = ?", whereArgs, null, null, null);
		cursor.moveToFirst();
		Game game = cursorToGame(cursor);
		cursor.close();
		return game;
	}
	
	public void deleteGame(Game game) {
		openDatabaseIfNull();
		long id = game.getId();
		System.out.println("Match deleted with id: " + id);
		database.delete(GameDM.TABLE_GAME, MatchDM.COLUMN_ID + " = " + id, null);
	}
	
	private Game cursorToGame(Cursor cursor) {
		Game game = new Game();
		game.setId(cursor.getLong(0));
		game.setMatch(cursor.getInt(1));
		game.setGameNumber(cursor.getInt(2));
		game.setHomeScore(cursor.getInt(3));
		game.setAwayScore(cursor.getInt(4));
		return game;
	}
	
	private void openDatabaseIfNull(){
		if(database==null){
			open();
		}
	}
}
